package DSN;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import javax.sql.DataSource;
import java.io.File;
import java.net.ServerSocket;
import java.time.LocalTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.text.SimpleDateFormat;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class div_data_main {
    private static final int TARGET_HOUR = 1; // 凌晨1点
    public static void main(String[] args) throws Exception {
        int port = 8080; // 默认值
        for (String arg : args) {
            if (arg.startsWith("--port=")) {
                port = Integer.parseInt(arg.substring(7));
                System.out.println("port==="+port );
            }
        }
        new ServerSocket(port); // 启动服务
        String s = new LogClass().getBasePath() + File.separator + "LogFile" + File.separator + new SimpleDateFormat("yyyy-MM-dd").format(new Date());// 日志保存路径
        System.out.println("日志路径:["+s+"]" );
         String[] dateStr=new String[]{"2025-08-21","2025-08-22","2025-08-23"};
        GetDivStatusFromMpay getDivStatusFromMpay = new GetDivStatusFromMpay();
        getDivStatusFromMpay.asyncDivData();
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(2);
      /*  // 单次任务
        executor.schedule(() -> {
            System.out.println("单次任务@" + System.currentTimeMillis());
        }, 1, TimeUnit.SECONDS);

        // 固定速率周期任务
        executor.scheduleAtFixedRate(() -> {
            System.out.println("固定速率任务");
        }, 2, 3, TimeUnit.SECONDS);*/
        SimpleDateFormat format_Date = new SimpleDateFormat("yyyy-MM-dd");
        System.out.println( format_Date.format(addDay(new Date(),-11)));
        // 固定延迟周期任务
        executor.scheduleWithFixedDelay(() -> {
            try{
                LogClass.info("NMGJTJT--->MPAY未拆分数据开始发送" + LocalTime.now());
                JdbcTemplate jdbcTemplate = new JdbcTemplate(new DBUtil().Hikar_DataSource_JTJT());
                JdbcTemplate jdbcTemplateMpay = new JdbcTemplate(new DBUtil().Hikar_DataSource_MPAY());
                String div_passid_nodiv="merge into DIV_PASSID_ALL_NODIV t1 " +
                        "using(select :passid as passid,to_date(:classdate,'yyyy-mm-dd HH24:mi:ss') as classdate,:VEHICLEID as VEHICLEID," +
                        "to_date(:GPAENTIME,'yyyy-mm-dd HH24:mi:ss') as GPA_ENTIME_LW,:GPAENPOINTID as GPA_ENPOINTID_LW," +
                        "to_date(:GPAEXTIME,'yyyy-mm-dd HH24:mi:ss') as GPA_EXTIME_LW,:GPAEXPOINTID as GPA_EXPOINTID_LW," +
                        ":VEHICLETYPE as VEHICLETYPE,:GPAFEELW as GPA_FEE_LW" +
                        " from dual) t2 on(t1.passid=t2.passid ) when matched then update set t1.VEHICLEID=t2.VEHICLEID,t" +
                        "1.GPA_ENTIME_LW=t2.GPA_ENTIME_LW,t1.GPA_ENPOINTID_LW=t2.GPA_ENPOINTID_LW,t1.GPA_EXTIME_LW=t2.GPA_EXTIME_LW," +
                        "t1.GPA_EXPOINTID_LW=t2.GPA_EXPOINTID_LW,t1.VEHICLETYPE=t2.VEHICLETYPE,t1.GPA_FEE_LW=t2.GPA_FEE_LW" +
                        " when not matched then insert( passid,classdate,VEHICLEID, GPA_ENTIME_LW, GPA_ENPOINTID_LW, GPA_EXTIME_LW, GPA_EXPOINTID_LW, VEHICLETYPE,GPA_FEE_LW) " +
                        "values (t2.passid,t2.classdate,t2.VEHICLEID, t2.GPA_ENTIME_LW, t2.GPA_ENPOINTID_LW, t2.GPA_EXTIME_LW, t2.GPA_EXPOINTID_LW, t2.VEHICLETYPE,t2.GPA_FEE_LW)";
               // String date = format_Date.format(addDay(new Date(), -11));


                //for(String date:dateStr){
                String date=format_Date.format(addDay(new Date(),-11));
                    System.out.println("处理数据的日期:["+date+"]" );
                    String sqlQuery="select PASSID,CLASSDATE,VEHICLEID,GPA_ENTIME_LW,GPA_ENPOINTID_LW,GPA_EXTIME_LW,GPA_EXPOINTID_LW,VEHICLETYPE,GPA_FEE_LW from DIV_PASSID_ALL_JT1 where classdate=to_date('"+date+"','yyyy-mm-dd') and status=5";
                    List<Map<String, Object>> gpa_list = jdbcTemplate.queryForList(sqlQuery);
                    ArrayList<Object[]> div_passid_nodiv_params = new ArrayList<>();
                    if(!gpa_list.isEmpty()){
                        gpa_list.forEach(gpa-> {
                            String passid = gpa.get("PASSID").toString();
                            String classdate = gpa.get("CLASSDATE").toString().substring(0,19);
                            String vehicleid = gpa.get("VEHICLEID").toString();
                            String gpaentime = gpa.get("GPA_ENTIME_LW").toString().substring(0,19);
                            String gpaenpointid = gpa.get("GPA_ENPOINTID_LW").toString();
                            String gpaextime = gpa.get("GPA_EXTIME_LW").toString().substring(0,19);
                            String gpaexpointid = gpa.get("GPA_EXPOINTID_LW").toString();
                            String vehicletype = gpa.get("VEHICLETYPE").toString();
                            String gpaFeeLw = gpa.get("GPA_FEE_LW").toString();
                            div_passid_nodiv_params.add(new Object[]{passid,classdate,vehicleid,gpaentime,
                                    gpaenpointid,gpaextime,gpaexpointid,vehicletype,gpaFeeLw});
                        });
                    };
                    DataSourceTransactionManager dataSourceTransactionManager = new DataSourceTransactionManager(Objects.requireNonNull(jdbcTemplateMpay.getDataSource()));
                    TransactionTemplate transactionTemplate = new TransactionTemplate(dataSourceTransactionManager);
                    transactionTemplate.execute(new TransactionCallback<Object>() {
                        @Override
                        public Object doInTransaction(TransactionStatus transactionStatus) {
                            Object savepoint = transactionStatus.createSavepoint();
                            try {
                                jdbcTemplateMpay.batchUpdate(div_passid_nodiv, div_passid_nodiv_params);
                                LogClass.info("NMGJTJT--->MPAY未拆分数据发送结束" + LocalTime.now());
                            } catch (Exception e) {
                                LogClass.error("NMGJTJT--->MPAY未拆分数据事务执行错误，错误信息" + e.getMessage());
                                transactionStatus.setRollbackOnly();
                            }
                            return null;
                        }
                    });
              //  }

            }catch (Exception e){
                LogClass.exception(e);
            }

        },calculateInitialDelay(),  24 * 60 * 60 * 1000, TimeUnit.MILLISECONDS);// 24小时周期（会被动态调整覆盖）


    }

    private static long calculateInitialDelay() {
        LocalTime now = LocalTime.now();
        LocalTime targetTime = LocalTime.of(TARGET_HOUR, 0);

        long delay = now.until(targetTime, ChronoUnit.MILLIS);
        if (delay < 0) {
            delay += TimeUnit.DAYS.toMillis(1); // 如果今天已过目标时间，延迟到明天
        }
        return delay;
    }


    private static Date addDay(Date date, int days) {
        Calendar startDT = Calendar.getInstance();
        startDT.setTime(date);
        startDT.add(Calendar.DAY_OF_MONTH, days);
        return startDT.getTime();
    }



}




